package com.fan.shop.views.bean;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;

import com.fan.shop.businesslogic.FileUploadProcess;
import com.fan.shop.businesslogic.ItemUpdateProcess;
import com.fan.shop.domain.Item;
import com.fan.shop.global.ShopGlobalUtils;
import com.fan.shop.global.ShopGlobalVariables;
import com.fan.shop.model.commonbrowser.CommonBrowser;
import com.fan.shop.services.BrandService;
import com.fan.shop.services.CategoryService;
import com.fan.shop.services.ItemService;
import com.fan.shop.services.LocationService;
import com.fan.shop.services.TransactionReferenceService;

@ManagedBean(name = "itemBean")
@RequestScoped
public class ItemBean extends ShopBean {

	private static Logger logger = Logger.getLogger(ItemBean.class);

	@ManagedProperty(value = "#{locationService}")
	private LocationService locationService;

	@ManagedProperty(value = "#{categoryService}")
	private CategoryService categoryService;

	@ManagedProperty(value = "#{transactionReferenceService}")
	private TransactionReferenceService transactionReferenceService;
	@ManagedProperty(value = "#{itemService}")
	private ItemService itemService;
	
	@ManagedProperty(value = "#{brandService}")
	private BrandService brandService;

	private ShopBean parentBean;

	private String itemName;
	private String itemDescription;
	private BigDecimal price;
	private String origLocation;
	private String category;
	private String icon;
	private Date registeredTime;
	private String attribute;
	private boolean suspended;
	private String brand;
	private String itemCode;
	private int locationId;
	private int categoryId;

	private Part iconFile;
	private String previewIconPath;
	private String tempIconFilePath;

	public ItemBean() {
		super();
		setReturnedValues();

	}

	public void setReturnedValues() {
		Map<String, Object> map = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestMap();
		if (map.containsKey("common_browser")) {
			CommonBrowser commonBrowser = (CommonBrowser) map
					.get("common_browser");

			itemService = ((ItemBean) commonBrowser.getCaller())
					.getItemService();
			categoryService = ((ItemBean) commonBrowser.getCaller())
					.getCategoryService();
			locationService = ((ItemBean) commonBrowser.getCaller())
					.getLocationService();

			itemCode = ((ItemBean) commonBrowser.getCaller()).getItemCode();
			loadItemDetails();
			itemName = ((ItemBean) commonBrowser.getCaller()).getItemName();
			itemDescription = ((ItemBean) commonBrowser.getCaller())
					.getItemDescription();

			brand = ((ItemBean) commonBrowser.getCaller()).getBrand();
			price = ((ItemBean) commonBrowser.getCaller()).getPrice();
			origLocation = ((ItemBean) commonBrowser.getCaller())
					.getOrigLocation();

			category = ((ItemBean) commonBrowser.getCaller()).getCategory();

			icon = ((ItemBean) commonBrowser.getCaller()).getIcon();
			attribute = ((ItemBean) commonBrowser.getCaller()).getAttribute();
			suspended = ((ItemBean) commonBrowser.getCaller()).getSuspended();

			previewIconPath = ((ItemBean) commonBrowser.getCaller())
					.getPreviewIconPath();
			tempIconFilePath = ((ItemBean) commonBrowser.getCaller())
					.getTempIconFilePath();

			parentBean = ((ShopBean) commonBrowser.getCaller()).getParentBean();

			if (commonBrowser.getReturnList().size() == 0) {
				return;
			}

			if (commonBrowser.getTriggerField().equals("category_name")) {
				categoryId = Integer.parseInt(commonBrowser.getReturnList()
						.get(0));
				category = categoryService.getCategory(categoryId).getName();

			}
			if (commonBrowser.getTriggerField().equals("location_name")) {
				locationId = Integer.parseInt(commonBrowser.getReturnList()
						.get(0));
				origLocation = locationService.getLocation(locationId)
						.toString();
			}
			if (commonBrowser.getTriggerField().equals("brand_name")) {
				brand = commonBrowser.getReturnList().get(0);
			}

		}
	}

	public static Logger getLogger() {
		return logger;
	}

	public static void setLogger(Logger logger) {
		ItemBean.logger = logger;
	}

	public LocationService getLocationService() {
		return locationService;
	}

	public void setLocationService(LocationService locationService) {
		this.locationService = locationService;
	}

	public CategoryService getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public ItemService getItemService() {
		return itemService;
	}

	public void setItemService(ItemService itemService) {

		this.itemService = itemService;
		// loadItemDetails();
	}

	public TransactionReferenceService getTransactionReferenceService() {
		return transactionReferenceService;
	}

	public void setTransactionReferenceService(
			TransactionReferenceService transactionReferenceService) {
		this.transactionReferenceService = transactionReferenceService;
	}

	public BrandService getBrandService() {
		return brandService;
	}

	public void setBrandService(BrandService brandService) {
		this.brandService = brandService;
	}

	public ShopBean getParentBean() {
		return parentBean;
	}

	public void setParentBean(ShopBean parentBean) {
		this.parentBean = parentBean;
	}

	public String getItemName() {
		return itemName;
	}

	public void setItemName(String itemName) {
		this.itemName = itemName;
	}

	public String getItemDescription() {
		return itemDescription;
	}

	public void setItemDescription(String itemDescription) {
		this.itemDescription = itemDescription;
	}

	public BigDecimal getPrice() {
		return price;
	}

	public void setPrice(BigDecimal price) {
		this.price = price;
	}

	public String getOrigLocation() {
		return origLocation;
	}

	public void setOrigLocation(String origLocation) {
		this.origLocation = origLocation;
	}

	public String getCategory() {
		return category;
	}

	public void setCategory(String category) {
		this.category = category;
	}

	public String getIcon() {
		return icon;
	}

	public void setIcon(String icon) {
		this.icon = icon;
	}

	public Date getRegisteredTime() {
		registeredTime = itemService.getItem(itemCode).getRegisteredTime();
		return registeredTime;
	}

	public void setRegisteredTime(Date registeredTime) {
		this.registeredTime = registeredTime;
	}

	public String getAttribute() {
		return attribute;
	}

	public void setAttribute(String attribute) {
		this.attribute = attribute;
	}

	public boolean getSuspended() {
		return suspended;
	}

	public void setSuspended(boolean suspended) {
		this.suspended = suspended;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getItemCode() {

		return itemCode;
	}

	public void setItemCode(String itemCode) {
		this.itemCode = itemCode;
	}

	public int getLocationId() {
		return locationId;
	}

	public void setLocationId(int locationId) {
		this.locationId = locationId;
	}

	public int getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(int categoryId) {
		this.categoryId = categoryId;
	}

	public Part getIconFile() {
		return iconFile;
	}

	public void setIconFile(Part iconFile) {
		this.iconFile = iconFile;
	}

	public String getPreviewIconPath() {
		return previewIconPath;
	}

	public void setPreviewIconPath(String previewIconPath) {
		this.previewIconPath = previewIconPath;
	}

	public String getTempIconFilePath() {
		return tempIconFilePath;
	}

	public void setTempIconFilePath(String tempIconFilePath) {
		this.tempIconFilePath = tempIconFilePath;
	}

	public String submitAction() {

		ItemUpdateProcess itemUpdateProcess = new ItemUpdateProcess();
		itemUpdateProcess.setItemCode(itemCode);
		itemUpdateProcess.setItemName(itemName);
		itemUpdateProcess.setItemDescription(itemDescription);
		itemUpdateProcess.setPrice(price);
		itemUpdateProcess.setItemCategory(categoryService.getCategory(category)
				.getId());

		itemUpdateProcess.setItemOrigLocation(locationService
				.getLocationByValue(origLocation).getId());
		itemUpdateProcess.setItemAttributes(attribute);
		itemUpdateProcess.setRegisteredTime(getRegisteredTime());
		itemUpdateProcess.setItemService(itemService);
		itemUpdateProcess.setLocationService(locationService);
		itemUpdateProcess.setCategoryService(categoryService);
		itemUpdateProcess.setIconTempFile(new File(tempIconFilePath));
		
		itemUpdateProcess.setBrand(brand);
		itemUpdateProcess.setBrandService(brandService);
		
		itemUpdateProcess.setItemIcon(icon);

		int result = itemUpdateProcess.process();
		setIcon(itemUpdateProcess.getItemIcon());

		if (result == ShopGlobalVariables.FAILED) {
			return "item.faces?faces-redirect=true";
		} else {
			return "items.faces?faces-redirect=true";
		}

	}

	public String backToItemsAction() {
		return "items.faces?faces-redirect=true";
	}
	
	public String openBrandsAction()
	{
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("brand_name");
		commonBrowser.setParentPage("../../views/management/item.faces");
		commonBrowser.setSelectionMode("single");
		commonBrowser.setShopService(brandService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";
	}

	public String openCategoriesAction() {
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("category_name");
		commonBrowser.setParentPage("../../views/management/item.faces");
		commonBrowser.setSelectionMode("single");
		commonBrowser.setShopService(categoryService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";

	}

	public String openLocationsAction() {
		CommonBrowser commonBrowser = new CommonBrowser();
		commonBrowser.setTriggerField("location_name");
		commonBrowser.setParentPage("../../views/management/item.faces");
		commonBrowser.setSelectionMode("single");
		commonBrowser.setShopService(locationService);
		commonBrowser.setCaller(this);
		FacesContext.getCurrentInstance().getExternalContext().getRequestMap()
				.put("common_browser", commonBrowser);
		return "../../views/commonbrowser/commonbrowser.faces";
	}


	public void loadItemDetails() {
		Map<String, Object> map = FacesContext.getCurrentInstance()
				.getExternalContext().getRequestMap();
		if (map.containsKey("item_code")) {
			itemCode = map.get("item_code").toString();
			// map.remove("item_code");
		}
		if (itemCode != null && itemCode.length() > 0) {
			if (itemService.hasItem(itemCode)) {
				Item item = itemService.getItem(itemCode);
				itemName = item.getItemName();
				itemDescription = item.getItemDescription();
				price = item.getPrice();
				origLocation = locationService.getLocation(
						item.getOrigLocation()).getCity();
				category = categoryService.getCategory(item.getCategory())
						.getName();
				icon = item.getIcon();
				registeredTime = item.getRegisteredTime();
				attribute = item.getAttributes();
				if (item.getSuspended() == 0) {
					suspended = false;
				} else {
					suspended = true;
				}
			}
		}
	}

	public String loadIconAction() {
		FileUploadProcess fileUploadProcess = new FileUploadProcess();
		fileUploadProcess.setFileName("temp");
		fileUploadProcess.setPart(iconFile);
		fileUploadProcess.setUploadType(ShopGlobalVariables.TEMP);
		fileUploadProcess.setFileContentType(ShopGlobalUtils
				.getFileContentType(previewIconPath));
		int result = fileUploadProcess.process();
		if (result == ShopGlobalVariables.SUCCESS) {
			previewIconPath = fileUploadProcess.getRelativePath();
			icon = previewIconPath;
		} else {
			System.out.println(icon);
		}

		// File file = new File(fileUploadProcess.getFullFilePath());
		// System.out.println(iconFile.getSize());
		tempIconFilePath = fileUploadProcess.getFullFilePath();

		return "item.faces";
	}

}
